<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
import { getVideoList, getClassPage, getSourceList, postVideoAdd, postVideoDel, getVideoEdit, getVideoShelves } from "@/api/curriculum/index";
import { UserQuery, UserPageVO } from "@/api/user/types";
import Editor from "@/components/WangEditor/index.vue";


// 图片域名
const imgUrl = ref(import.meta.env.VITE_APP_BASE_API);

const multipleTableRef = ref<any>()


const queryFormRef = ref(ElForm); // 查询表单

const loading = ref(false);
const ids = ref([]);
const total = ref(0);
const dialog = reactive<DialogOption>({
  title: "新增",
  visible: false,
});

const queryParams = reactive<any>({
  page: 1,
  page_size: 10,
});

const tableList = ref<UserPageVO[]>();


/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getVideoList(queryParams)
    .then(({ data }) => {
      tableList.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  queryParams.deptId = undefined;
  handleQuery();
}


const selectList = ref<any[]>([])
const materialList = ref<any[]>([])

// 素材弹窗
const material = reactive<any>({
  title: "选择素材",
  visible: false,
  total: 0,
  page: 1,
  page_size: 10,
  list: [],
  ids: [],
});


// 添加视频
function hanldeOpenDialog(data: any | null = null) {
  dialog.visible = true;

  if (data) {
    dialog.title = "编辑";
    formData.id = data.id;
    formData.title = data.title;
    formData.subject_id = data.subject_id;
    formData.labels = data.labels;
    formData.url = imgUrl.value + data.avatar;
    formData.avatar = data.avatar;
    formData.special_task_id = data.special_task_id;
    formData.sort = data.sort;
    formData.status = data.status;
    formData.desc = data.desc;
    material.list = data.video;
    material.ids = data.video.map((item: any) => item.id);

  }

  // 获取课程分类
  getClassPage({}).then(res => {
    selectList.value = res.data
  })

  // 获取素材列表
  getSourceList({}).then(({ data }) => {
    materialList.value = data.data;
    material.total = data.total;
  })
}

// 新增表单
const ruleFormRef = ref(ElForm);

// 提交数据
const formData = reactive<any>({})

// 提交正则
const rules = reactive<any>({
  title: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  subject_id: [{ required: true, message: '请选择顶级分类', trigger: 'change' }]
})


// 关闭弹窗
const closeDialog = () => {
  nextTick(() => {
    ruleFormRef.value.resetFields();
    material.list = []
  })
  dialog.visible = false;
}

// 添加视频 
const handleSubmit = async () => {
  await ruleFormRef.value.validate(async (valid: any) => {
    if (valid) {
      if (dialog.title == "编辑") {
        getVideoEdit(formData).then(res => {
          resetQuery();
          closeDialog();
          ElMessage.success("编辑成功");
        })

      } else {
        postVideoAdd(formData).then(res => {
          resetQuery();
          closeDialog();
          ElMessage.success("添加成功");
        })
      }
    }
  })

}

// 获取图片链接
const updatepostUrl = (url: string) => {
  formData.url = imgUrl.value + url;
  formData.avatar = url;
}

// 打开选择素材弹窗
const hanldeOpenListDialog = () => {
  material.visible = true;
}

const opened = () => {
  nextTick(() => {
    materialList.value.forEach((item: any) => {
      let result = material.ids.find((row: any) => row == item.id);
      console.log(result, item.id)
      if (result) {
        multipleTableRef.value!.toggleRowSelection(item, true)
      }
    });
  })
}

// 获取选中的数据
const multipleSelection = ref([]);
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}

// 确认选素材id
const handleMateSubmit = () => {
  if (multipleSelection.value.length > 0) {
    material.list = multipleSelection.value;
    material.visible = false;
    formData.special_task_id = multipleSelection.value.map((item: any) => {
      return item.id
    })
  } else {
    ElMessage.warning("请选择素材");
  }
}

// 删除视频
const handleDelete = async (id: number) => {
  await ElMessageBox.confirm("确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    let res = await postVideoDel({ id: id }) as any;
    ElMessage.success(res.msg);
    handleQuery();
  }).catch(() => {
    ElMessage({
      type: "info",
      message: "已取消删除",
    });
  });
}

// 切换上下架
const hanldeStatus = async (val: boolean | string | number, id: number) => {
  let res = await getVideoShelves({ id, status: val }) as any;
  ElMessage.success(res.msg);
}

// 关闭素材弹窗
const closeMateDialog = () => {
  material.visible = false;
}

onMounted(() => {
  handleQuery(); // 初始化用户列表数据
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="专题搜索" prop="title">
              <el-input v-model="queryParams.title" placeholder="输入专题搜索查询" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="课程分类" prop="name">
              <el-select v-model="queryParams.unit_name" placeholder="选择专题分类查询" style="width: 200px"
                @change="handleQuery">
                <el-option label="Zone one" value="shanghai" />
                <el-option label="Zone two" value="beijing" />
              </el-select>
            </el-form-item> -->
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="选择上架状态" style="width: 200px" @change="handleQuery">
                <el-option label="下架" :value="100" />
                <el-option label="上架" :value="200" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button @click="hanldeOpenDialog()" type="success"><i-ep-plus />新增</el-button>
              </div>
            </div>
          </template>
          <el-table ref="multipleTableRef" v-loading="loading" :data="tableList">
            <el-table-column label="排序" align="center" prop="sort" />
            <el-table-column label="名称" align="center" prop="title" />
            <el-table-column label="分类" align="center" prop="subject_name" />
            <el-table-column label="封面" align="center">
              <template #default="scope">
                <img :src="imgUrl + scope.row.avatar" alt="" style="width: 50px; height: 50px" />
              </template>
            </el-table-column>
            <el-table-column label="时间" align="center" prop="create_time" />
            <el-table-column label="状态" align="center">
              <template #default="scope">
                <el-switch @change="hanldeStatus($event, scope.row.id)" v-model="scope.row.status" size="large"
                  :inactive-value="100" :active-value="200" active-text="上架" inactive-text="下架" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" prop="update_time">
              <template #default="scope">
                <el-button @click="hanldeOpenDialog(scope.row)" type="primary" size="small"><i-ep-edit />编辑</el-button>
                <el-button @click="handleDelete(scope.row.id)" type="danger" size="small"><i-ep-delete />删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
            v-model:limit="queryParams.page_size" @pagination="handleQuery" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增修改弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="60%" append-to-body @close="closeDialog">
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="专题名称" prop="title">
          <el-input v-model="formData.title" placeholder="请输入素材分类名称" />
        </el-form-item>
        <el-form-item label="课程分类" prop="subject_id">
          <el-tree-select value-key="id" placeholder="请输入课程分类" v-model="formData.subject_id"
            :props="{ children: 'child', label: 'name' }" :data="selectList" check-strictly
            :render-after-expand="false">
          </el-tree-select>
        </el-form-item>
        <el-form-item label="标签" prop="labels">
          <el-input v-model="formData.labels" placeholder="请输入标签以英文逗号隔开" />
        </el-form-item>
        <el-form-item label="上架" prop="status">
          <el-switch v-model="formData.status" size="large" :inactive-value="100" :active-value="200" active-text="上架"
            inactive-text="下架" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="formData.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="专题封面" prop="url">
          <single-upload @updatepostUrl="updatepostUrl" v-model="formData.url" type="image" />
        </el-form-item>
        <el-form-item label="专题详情" prop="desc">
          <div style="border:1px solid #EBEEFF;height: 490px;">
            <editor v-model="formData.desc" style="height: 400px; width: 100%;" />
          </div>
        </el-form-item>
        <el-form-item label="素材选择" prop="desc">
          <el-button @click="hanldeOpenListDialog">选择素材</el-button>
          <el-table height="400" :data="material.list" v-if="material.list.length > 0">
            <el-table-column label="编号" align="center" prop="id" width="100" />
            <el-table-column label="素材名称" align="center" prop="title" />
            <el-table-column label="素材类型" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.type == 1" type="success">图片</el-tag>
                <el-tag v-else-if="scope.row.type == 2" type="success">音频</el-tag>
                <el-tag v-else-if="scope.row.type == 3" type="success">视频</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="pic" label="素材封面" align="center">
              <template #default="scope">
                <img :src="imgUrl + scope.row.image" alt="" style="width: 50px; height: 30px" />
              </template>
            </el-table-column>
            <el-table-column label="链接" align="center" prop="link" />
            <el-table-column label="状态" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.is_show == 1" type="success">显示</el-tag>
                <el-tag v-else-if="scope.row.is_show == 2" type="success">隐藏</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 选择素材 -->
    <el-dialog v-model="material.visible" @opened="opened" :title="material.title" width="50%" append-to-body>
      <el-card shadow="never">
        <template #header>
          <div class="flex justify-between">
            <router-link to="/materialList">
              <el-button type="success">去添加素材</el-button>
            </router-link>
          </div>
        </template>
        <el-table ref="multipleTableRef" height="300" v-loading="loading" :data="materialList"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="编号" align="center" prop="id" width="100" />
          <el-table-column label="素材名称" align="center" prop="title" />
          <el-table-column label="素材类型" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.type == 1" type="success">图片</el-tag>
              <el-tag v-else-if="scope.row.type == 2" type="success">音频</el-tag>
              <el-tag v-else-if="scope.row.type == 3" type="success">视频</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="pic" label="素材封面" align="center">
            <template #default="scope">
              <img :src="imgUrl + scope.row.image" alt="" style="width: 50px; height: 30px" />
            </template>
          </el-table-column>
          <el-table-column label="链接" align="center" prop="link" />
          <el-table-column label="状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.is_show == 1" type="success">显示</el-tag>
              <el-tag v-else-if="scope.row.is_show == 2" type="success">隐藏</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-if="material.total > 0" v-model:total="material.total" v-model:page="material.page"
          v-model:limit="material.page_size" @pagination="handleQuery" />
      </el-card>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleMateSubmit">确 定</el-button>
          <el-button @click="closeMateDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
